﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Serialization;

namespace DocumentFormat.OpenXml.Lite.Helper
{
    public static class Extensions
    {
        public static string GetDescription(this Enum _enum)
        {
            FieldInfo fi = _enum.GetType().GetField(_enum.ToString());
            DescriptionAttribute[] dattributes = (DescriptionAttribute[])
                fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (dattributes.Length > 0)
            {
                return dattributes[0].Description;
            }

            XmlEnumAttribute[] xattributes = (XmlEnumAttribute[])
                fi.GetCustomAttributes(typeof(XmlEnumAttribute), false);
            if (xattributes.Length > 0)
            {
                return xattributes[0].Name;
            }
            
            return _enum.ToString();
        }

        public static bool IsInheritedFrom(this Type _type, Type parent)
        {
            while (parent != null && parent != typeof(object))
            {
                var current = parent.IsGenericType ? parent.GetGenericTypeDefinition() : parent;
                if (_type == current)
                {
                    return true;
                }
                parent = parent.BaseType;
            }
            return false;
        }
    }
}
